package com.zhucan.tenant.datasource.extension;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;

/**
 * @author My Lord zhuCan
 * @description 多租户数据库名生成器
 * @since 2022-12-09 11:32
 **/
public interface DatasourceTenantDatabaseNameGenerator {

    /**
     * 生成多租户下 mongo 的数据库名
     *
     * @param tenant 租户标识
     * @return database name
     */
    String generateDatabaseName(String tenant);


    class DefaultDatasourceTenantDatabaseNameGenerator implements DatasourceTenantDatabaseNameGenerator {

        private final Environment environment;

        private final DatasourceTenantProperties datasourceTenantProperties;


        public DefaultDatasourceTenantDatabaseNameGenerator(Environment environment, DatasourceTenantProperties datasourceTenantProperties) {
            this.environment = environment;
            this.datasourceTenantProperties = datasourceTenantProperties;
        }

        @Override
        public String generateDatabaseName(String tenant) {

            String serverName = environment.resolvePlaceholders("${spring.application.name}");

            return  (StringUtils.isNotBlank(datasourceTenantProperties.getNamePrefix())? datasourceTenantProperties.getNamePrefix()+
                datasourceTenantProperties.getSplit() : "") + tenant;
        }
    }
}
